package com.jeady.jTools.imitateChat

import android.Manifest
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.core.app.ActivityCompat
import com.jeady.jTools.R

class ChatConfigDialog(context: Context, listener: OnClickFinish): Dialog(context){
    val TAG = "chatConfigDialog"
    var listener: OnClickFinish = listener
    val msgList = ArrayList<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.dialog_chat_config)


        val spSelectMsgMode = findViewById<Spinner>(R.id.sp_chat_msg_mode_mode)

        val lp = window?.attributes
        if (lp != null) {
            lp.width = ViewGroup.LayoutParams.MATCH_PARENT
            lp.height = ViewGroup.LayoutParams.MATCH_PARENT
        }
        window?.attributes = lp
        setCanceledOnTouchOutside(false)

        // 检查读取头像权限
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ownerActivity?.let { it1 -> ActivityCompat.requestPermissions(it1,
                arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1100)
            };
        }

        // 返回
        findViewById<TextView>(R.id.tv_btn_config_chat_exit).setOnClickListener{
            dismiss()
        }

        // 点击配置完成按钮, 传出已配置好的参数
        findViewById<TextView>(R.id.tv_btn_config_chat_finish).setOnClickListener {
            val bundle = Bundle()
            bundle.putString("objName", findViewById<EditText>(R.id.et_config_chat_objName).text.toString())
            bundle.putString("myName", findViewById<EditText>(R.id.et_config_chat_myName).text.toString())
            when(findViewById<RadioGroup>(R.id.rbg_config_chat_mode).checkedRadioButtonId){
                // 静态消息
                R.id.rb_chat_mode_static -> bundle.putInt("msgType", 0)
                // 半自动消息
                R.id.rb_chat_mode_auto_half -> bundle.putInt("msgType", 1)
                // 全自动消息
                R.id.rb_chat_mode_auto -> bundle.putInt("msgType",
                    findViewById<Spinner>(R.id.sp_config_chat_auto_seconds).selectedItemPosition + 2)
            }
            bundle.putStringArrayList("msgList", msgList)
            listener.handleData(bundle)
            dismiss()
        }

        // 更换对象头像
        findViewById<ImageView>(R.id.iv_config_chat_objAvator).setOnClickListener{
            Log.e(TAG, "onCreate: clcikc avatar")
            val intentSelectPhoto = Intent(Intent.ACTION_PICK)
            intentSelectPhoto.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
            ownerActivity?.startActivityForResult(intentSelectPhoto, 1001)
        }

        // 更换自己的头像
        findViewById<ImageView>(R.id.iv_config_chat_myAvator).setOnClickListener{
            Log.e(TAG, "onCreate: clcikc avatar")
            val intentSelectPhoto = Intent(Intent.ACTION_PICK)
            intentSelectPhoto.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
            ownerActivity?.startActivityForResult(intentSelectPhoto, 1002)
        }

        // 根据静态记录/动态， 选择某视图显示/隐藏
        findViewById<RadioGroup>(R.id.rbg_config_chat_mode).setOnCheckedChangeListener { _, checkedId ->
            run {
                val llConfigMsgParam = findViewById<LinearLayout>(R.id.ll_config_chat_msgParam)
                val spSeconds = findViewById<Spinner>(R.id.sp_config_chat_auto_seconds)
                if (checkedId == R.id.rb_chat_mode_static) {
                    llConfigMsgParam.visibility = View.GONE
                    spSeconds.visibility = View.GONE
                } else if(checkedId == R.id.rb_chat_mode_auto){
                    llConfigMsgParam.visibility = View.GONE
                    spSeconds.visibility = View.VISIBLE
                }else{
                    llConfigMsgParam.visibility = View.VISIBLE
                    spSeconds.visibility = View.GONE
                }
            }
        }

        // 根据谁的消息，决定消息发送方式选择
        findViewById<RadioGroup>(R.id.rbg_config_msg_whos).setOnCheckedChangeListener{_, checkedId ->
            run{
                val arrAdapter = ArrayAdapter<String>(this.context, R.layout.support_simple_spinner_dropdown_item)
                if(checkedId == R.id.rb_config_chat_msg_his){
                    arrAdapter.addAll(*ownerActivity?.resources?.getStringArray(R.array.config_chat_mode_config1))
                }else{
                    arrAdapter.addAll(*ownerActivity?.resources?.getStringArray(R.array.config_chat_mode_config2))
                }
                spSelectMsgMode.adapter = arrAdapter
            }
        }

        // 清空消息列表
        findViewById<TextView>(R.id.tv_btn_config_chat_clear_list).setOnClickListener {
            msgList.clear()
            findViewById<LinearLayout>(R.id.ll_config_chat_msgList).removeAllViews()
        }

        // 添加消息
        findViewById<TextView>(R.id.tv_btn_config_add_msg).setOnClickListener {
            val msgTv = TextView(it.context)
            val text = findViewById<EditText>(R.id.et_config_chat_input_msg).text.toString()
            if(text.replace(" ", "").isEmpty()) {
                return@setOnClickListener
            }
            msgTv.textSize = 16F
            if(findViewById<RadioButton>(R.id.rb_config_chat_msg_his).isChecked){
                msgTv.text = text
                msgTv.gravity = Gravity.START
                msgList.add("0%d%3d$text".format(spSelectMsgMode.selectedItemPosition, 0))
            }else{
                msgTv.text = text
                msgTv.gravity = Gravity.END
                msgList.add("1%d%3d$text".format(spSelectMsgMode.selectedItemPosition, 0))
            }
            findViewById<LinearLayout>(R.id.ll_config_chat_msgList).addView(msgTv)
            val configMsgList = findViewById<ScrollView>(R.id.sv_config_chat_msgList)
            configMsgList.post {
                configMsgList.fullScroll(View.FOCUS_DOWN)
            }
            findViewById<EditText>(R.id.et_config_chat_input_msg).setText("")
        }
    }
    fun setAvator(uri: Uri, which: Int){
        if(which == 0){
            findViewById<ImageView>(R.id.iv_config_chat_objAvator).setImageURI(uri)
        }else{
            findViewById<ImageView>(R.id.iv_config_chat_myAvator).setImageURI(uri)
        }
    }

    interface OnClickFinish{
        fun handleData(data: Bundle)
    }
}